JavaScript-提升hoisting


Posted by RLun on 2022-10-11

Hoisting觀念

雖然把宣告寫在後面,JavaScript在執行程式之前,會做一個提升(Hoisting)。

Hoisting 特性是宣告提升,並不會給初始值進行提升。

  • 變數從上到下做瀏覽

    console.log(x);   //undefined
    var x = 3;
    console.log(x);   //3
    
  • Hoisting結果

    console.log(x);   //undefined
    var x = 3;
    console.log(x);   //3
    

函式陳述式 (function declaration) 會被提升

  • function,會把function提升最上面

    count();                 //hello
    function count(){
    console.log(’hello!’);
    }
    
  • Hoisting結果

    function count(){
    console.log(’hello!’);
    }
    count();
    

函式表達式Function expression不會被提升,會被提升的式宣告提升

  • function,會把function提升最上面

    count();                             //Uncaught TypeError: count is not a function
    const count = function(){
      console.log(’hello’)
    }
    
  • Hoisting結果,呼叫時執行時並沒有function

    const count;
    count();
    count = function(){
    console.log(’hello!’);
    }
    

補充
函式(function)與變數(variable)同名時,函式優先。

  • function 與 variable 同時存在時

    console.log(count)
    var count;
    function count(){};
    
  • Hoisting結果

    function count(){};
    console.log(count)
    var count;
    

#javascript #js #hoisting #提升 #宣告 #Web







Related Posts

JavaScript 基礎筆記

JavaScript 基礎筆記

2023 D4SG 成果發表會心得

2023 D4SG 成果發表會心得

LeetCode JS Easy 2704. To Be Or Not To Be

LeetCode JS Easy 2704. To Be Or Not To Be


Comments